import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/config/constant.dart';
import 'package:kkhousekeep/models/base_respond_entity.dart';
import 'package:kkhousekeep/models/member.dart';
import 'package:kkhousekeep/models/member_list_entity.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';

import '../../net/me_member_connect.dart';
import '../../widget/custom_picker.dart';
import '../../widget/custom_toast.dart';
import '../../widget/dialog/custom_dialog.dart';
import '../public/take_picture_screen.dart';
import 'family_member_controller.dart';

class MemberDetailController extends GetxController {
  late MemberListObjList _member;
  List<String> genderList = [
    SexType.man.description,
    SexType.woman.description
  ];
  List<String> identificationTypeList = [
    IdCardType.identityCard.description,
    IdCardType.permitForProceedingToHongKongAndMacao.description,
    IdCardType.mainlandTravelPermitForTaiwanResidents.description,
    IdCardType.passport.description
  ];
  List<String> relationshipList = [
    MemberRelationship.familyMember.description,
    MemberRelationship.tenant.description
  ];
  var imagePath = "".obs;
  var isAddNewUser = false;
  var isEditMode = false.obs;
  var isTextEmpty = true.obs;
  var nameTextEditController = TextEditingController();
  var gender = "".obs; // 性别
  var identificationType = "".obs;
  var identificationNumberTextEditController = TextEditingController();
  var phoneTextEditController = TextEditingController();
  var relationship = "".obs; // 关系
  var image = "".obs; // 图片
  late MeMemberConnect meMemberConnect;

  late List<MemberListObjList> memberList; //成员列表

  bool isNameRepeat = false;

  var isButtonAsh = true.obs;

  @override
  void onInit() {
    meMemberConnect = Get.find<MeMemberConnect>();
    memberList = Get.find<FamilyMemberController>().memberList;
    if (Get.arguments != null) {
      _member = Get.arguments;
      nameTextEditController.text = _member.name;
      gender.value = SexType.values
          .firstWhere((element) => element.value == _member.sex)
          .description;
      identificationType.value = IdCardType.values
          .firstWhere((element) => element.value == _member.iDCardType)
          .description;
      identificationNumberTextEditController.text = _member.iDCard;
      phoneTextEditController.text = _member.phone;
      relationship.value = MemberRelationship.values
          .firstWhere((element) => element.value == _member.relationship)
          .description;
      image.value = _member.image;
    } else {
      isAddNewUser = true;
      isEditMode.value = true;
    }
    nameTextEditController.addListener(() {
      if (Get.arguments != null) {
        if (!isEditMode.value ||
            nameTextEditController.text == Get.arguments.name) {
          return;
        }
      }
      isNameRepeat = false;
      for (var element in memberList) {
        if (nameTextEditController.text == element.name) {
          showNameRepeatToast();
          isNameRepeat = true;
          break;
        }
      }
      observeText();
    });
    identificationNumberTextEditController.addListener(() {
      observeText();
    });
    phoneTextEditController.addListener(() {
      observeText();
    });
    super.onInit();
  }

  save() {
    if (isButtonAsh.value) {
      return;
    }
    if (isNameRepeat) {
      showNameRepeatToast();
      return;
    }
    var idCardTypeValue = IdCardType.values
        .firstWhere(
            (element) => element.description == identificationType.value)
        .value;
    var relationshipValue = MemberRelationship.values
        .firstWhere((element) => element.description == relationship.value)
        .value;
    var sex = SexType.values
        .firstWhere((element) => element.description == gender.value)
        .value;
    submitUserRequest(
        phoneTextEditController.text,
        nameTextEditController.text,
        idCardTypeValue,
        identificationNumberTextEditController.text,
        sex,
        relationshipValue);
  }

  Future<void> submitUserRequest(
      String phoneValue,
      String nameValue,
      String idCardTypeValue,
      String idCardNumber,
      int sex,
      String relationshipValue) async {
    BaseRespondEntity? respondEntity;
    DialogUtil.showNetworkLoading();
    if (isAddNewUser) {
      respondEntity = await meMemberConnect.addMember(
        phone: phoneValue,
        name: nameValue,
        iDCardType: idCardTypeValue,
        iDCard: idCardNumber,
        sex: sex,
        relationship: relationshipValue,
        image: image.value,
      );
    } else {
      respondEntity = await meMemberConnect.updateMember(
        id: _member.id,
        phone: phoneValue,
        name: nameValue,
        iDCardType: idCardTypeValue,
        iDCard: idCardNumber,
        sex: sex,
        relationship: relationshipValue,
        image: image.value,
      );
    }
    DialogUtil.dismiss();
    if (respondEntity == null) {
      return;
    }
    if (respondEntity.code == ResponseCode.success) {
      Get.back(result: Constant.resultOK);
      return;
    }
    DialogUtil.showNetworkFail();
  }

  void uploadImage() {
    Get.bottomSheet(
      CustomDialog.customCupertinoActionSheet([
        CupertinoActionSheetActionModel("拍照", () {
          Get.back();
          takePhoto();
        }),
        CupertinoActionSheetActionModel("从相册上传", () {
          Get.back();
          selectImage();
        }),
      ]),
    );
  }

  selectImage() async {
    Get.to(
      TakePictureScreen(
        uerGallery: true,
        photoPathCallBack: <PickPictureModel>(model) {
          image.value = model.netPath;
          observeText();
        },
      ),
    );
  }

  takePhoto() async {
    Get.to(
      TakePictureScreen(
        photoPathCallBack: <PickPictureModel>(model) {
          image.value = model.netPath;
          observeText();
        },
      ),
    );
  }

  void showNameRepeatToast() {
    SmartDialog.showToast(
      "",
      builder: (context) => const CustomToast(
        msg: "姓名重复，请检查后重新输入",
        textStyle: TextStyle(color: Colors.red),
      ),
    );
  }

  void observeText() {
    if (nameTextEditController.text.isEmpty ||
        gender.value.isEmpty ||
        identificationType.value.isEmpty ||
        identificationNumberTextEditController.text.isEmpty ||
        phoneTextEditController.text.isEmpty ||
        relationship.value.isEmpty ||
        image.value.isEmpty) {
      isButtonAsh.value = true;
      return;
    }
    isButtonAsh.value = false;
  }

  void showPicker(confirmCallback,
      {required List<String> list, String? value}) {
    Get.bottomSheet(
      CustomPick(
        pickList: list,
        confirmCallBack: confirmCallback,
        cancelCallBack: (index) => {Get.back()},
      ),
    );
  }

  void showIdentificationPick() {
    showPicker(
      value: identificationType.value,
      list: identificationTypeList,
      (index) {
        identificationType.value = identificationTypeList[index];
        observeText();
      },
    );
  }

  void showRelationPicker() {
    showPicker(
      value: relationship.value,
      list: relationshipList,
      (index) {
        relationship.value = relationshipList[index];
        observeText();
      },
    );
  }

  void showGenderPicker() {
    showPicker(value: gender.value, list: genderList, (index) {
      gender.value = genderList[index];
      observeText();
    });
  }
}
